<?php
class Ext_Generic_Controller extends Zend_Controller_Action
{
    protected $registry;
    protected $session;
    protected $_roles;
    protected $_user;
    protected $_acl;
    protected $requires_auth = false;
    protected $_idUser;
    protected $_idCustomer;
    protected $_namespace;
    protected $_config;
    protected $_request;
    /**
     * flashMessenger administra los errores que se muestran al usuario
     *
     * @var stdClass
     */
    protected $_flashMessenger;
    public function init ()
    {
        /**
         * Configuracion de base de datos, archivos config y otros
         */
        $this->_config = new Ext_Generic_Config( );
        $this->_config->load();
        if ( $this->_config->getValue( "metadata_cache", "conf", "enabled" ) ) {
            
            // First, set up the Cache
            $frontendOptions = $this->_config->getValue( "metadata_cache", "frontend" );
            $backendOptions = $this->_config->getValue( "metadata_cache", "backend" );
            $cache = Zend_Cache::factory( 'Core', 'Sqlite', $frontendOptions, $backendOptions );
            if ( $this->_config->getValue( "metadata_cache", "conf", "clean" ) ) {
                $cache->clean( Zend_Cache::CLEANING_MODE_ALL );
            }
            // Next, set the cache to be used with all table objects
            Zend_Db_Table_Abstract::setDefaultMetadataCache( $cache );
        }
        $this->view->addHelperPath( 'Ext/View/Helper', 'Ext_View_Helper_' );
        Zend_Controller_Action_HelperBroker::addPrefix( 'Ext_Controller_Action_Helper' );
        $this->_flashMessenger = $this->_helper->getHelper( 'ExtFlashMessenger' );
         
        /**
         * Configuracion general.
         */
        $this->initView();
        $this->_namespace = new Zend_Session_Namespace( );
        $this->view->drupalServer = $this->_config->getValue(
            'external', 'drupal', 'site' );
        $this->view->staticServer = $this->_request->getBaseUrl();
        $this->view->addBasePath( '/', '' );
        $this->layoutConfig();
        $this->registry = Zend_Registry::getInstance();
        /**
         * Setea el path de las vistas de cada modulo
         */
        $view = new Zend_View( );
        $view->setScriptPath(
            $this->_config->getValue( 'site', 'scripts', 'helpers' ) .
            $this->getRequest()->getControllerName() . '/' );
    }
    public function preDispatch ()
    {
        $request = $this->_getPostsFiltered();
        if( isset( $request['external_user']) && isset($request['external_passwd'])) {
            return true;            
        }
        $this->_user = new stdClass();
        $this->_user->username = Authentication::getIdentity();
        if( $this->_user->username == false ) {
            $this->_namespace->urlBack = $_SERVER[ 'REQUEST_URI' ];
            $this->_redirect( '/register' );
        }
        $this->_idUser = Ext_Generic_Model::get ( 'user' )
            ->findFieldWithFilter ( 'user_id',  
                array( 'username' => $this->_user->username ));
        $userData = $this->_m('user')->find( $this->_idUser )->current();


        $this->_idCustomer = $userData->customer_id;
        $this->_user->id = $this->_idUser;
        $this->_user->first_name = $userData->first_name;
        $this->_user->last_name = $userData->last_name;
        /**
         * Establecemos permisos
         */
        $permission = new Pbook_Security_Permission( $this->_user );
        
        if( $permission === false ) {
            $this->_redirect( '/user/error/message/permisions' );
        }
        
        $this->_acl = $permission->load();
        $this->_roles = $permission->getRoles();
        /**
         * Seteamos el menu de la derecha
         */
        $layout = Zend_Layout::getMvcInstance();
        $this->view->roles = $this->_roles;
		/**
         * Le pasamos siempre al view, el objeto Zend_Form
         */
        $this->view->form = new Zend_Form();
        $this->view->user = $this->_user->first_name . " " . $this->_user->last_name;
        //    
    }

    /**
     * Agrega un error al layout
     *
     * @param string $msg
     */
    protected function addError( $msg )
    {
        $this->_flashMessenger->addError( $msg );
    }

    /**
     * Agrega un suceso al layout
     *
     * @param string $msg
     */
    protected function addSuccess( $msg )
    {
        $this->_flashMessenger->addSuccess( $msg );
    }

    /**
     * Agrega una advertencia al layout
     *
     * @param string $msg
     */
    protected function addWarning( $msg )
    {
        $this->_flashMessenger->addWarning( $msg );
    }

    /**
     * Agrega una  noticia al layout
     *
     * @param string $msg
     */
    protected function addNotice( $msg )
    {
        $this->_flashMessenger->addNotice( $msg );
    }
    
    /**
     * Averigua si el usuario tiene permisos o no para acceder a esta seccion
     *
     * @param $resource es el recurso al cual el usuario va a acceder
     * @param $privilege si el usuario puede o no acceder a este recurso
     * @uses isAllowed metodo de Zend_Acl
     * @return true  o false, dependiendo si tiene o no permisos para acceder
     */
    public function allow ( $resource, $privilege )
    {
        if( empty( $this->_user->username ) ) {
            return false;
        }
		$allowed = false;
		foreach( $this->_roles as $role ) {
			if ( $this->_acl->isAllowed( $role, $resource, $privilege ) ) {
				$allowed = true;
				break;
			}
		}
        return $allowed;
    }
    /**
     * Configuramos los layout que tiene el sistema
     */
    private function layoutConfig ()
    {
        $options = array( 
            'layout' => 'Cart', 
            'layout' => 'Frontend',
        	'layoutPath' => '../layout/' 
        );
        Zend_Layout::startMvc( $options );
        /**
         * Levanto los css, js, y el titulo de la pagina
         */
        /**
         * Agregp el titulo de la pagina
         */
        $this->view->headTitle()->append('Personal Book');
        /**
         * Agrego los css para esta pagina
         */ 
        $this->view->headLink()
            ->appendStylesheet( $this->view->drupalServer . '/css/layout-interior.css' )
            ->appendStylesheet( $this->view->drupalServer . '/css/style.css' )
            ->appendStylesheet( $this->view->drupalServer . '/css/style-interior.css' );
        /**
         * Agrego los js basicos
         */
        $this->view->headScript()
            ->appendFile('/js/mootools/mootools.js')
            ->appendFile('/js/mootools/fvalidator.js')
            ->appendFile('/js/globalFunctions.js')
            ->appendFile('/js/rollover.js');
    }
    /**
     * Parsea los request y devuelve variables validas
     *
     * @return $_POST y $_GET limpios
     */
    protected function _getPostsFiltered ()
    {
        $parmsPost = array();
        Zend_Loader::loadClass( 'Zend_Filter_StripTags' );
        $f = new Zend_Filter_StripTags( );
        foreach( $this->_request->getParams() as $key => $value ) {
            $parmsPost[ $key ] = $f->filter( $value );
        }
        return $parmsPost;
    }
    /**
	 *
	 */
    protected function _log( $msg )
    {
        error_log( $msg . "\n\n", 3, "/tmp/errores.log");
    }
    /**
     * Busca en EasyTech Generic Model, el modelo que le pasan
     * Se usa para reducir la linea que llama al modelo.
     *
     * @param string $model
     * @use Ext_Generic_Model
     * @return mixed stdClass
     */
    protected function _m( $model )
    {
        return Ext_Generic_Model::get( $model );
    }     
}
